/**
 *	programmed by zhangjing
 *	this class is used as a tool class for hibernate.
 */

package club325.webchat.database.hibernate.dao;

import java.io.Serializable;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public final class HibernateUtil
{
	private static SessionFactory sessionFactory;

	/**
	 * prevent people from building this class
	 */
	private HibernateUtil()
	{
	}

	/**
	 * initialize this class
	 */
	static
	{
		Configuration cfg = new Configuration();
		cfg.configure();
		sessionFactory = cfg.buildSessionFactory();
	}

	/**
	 * get sessionfactory.
	 * we always use method "getSession" instead.
	 * @return the SessionFactory
	 */
	public static SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	/**
	 * This method help to get Session
	 * @return the Session
	 */
	public static Session getSession()
	{
		return sessionFactory.openSession();
	}
	
	/**
	 * This method help to insert data into database  
	 * @param entity the object of data to be inserted.
	 */
	public static void add(Object entity)
	{
		Session session = null;
		Transaction tx = null;
		try
		{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.save(entity);
			tx.commit();
		}
		finally
		{
			if(session!=null)
				session.close();
		}
	}

	/**
	 * This method help to update data in the database  
	 * @param entity the object of data to be updated.
	 */	
	public static void Update(Object entity)
	{
		Session session = null;
		Transaction tx = null;
		try
		{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.update(entity);
			tx.commit();
		}
		finally
		{
			if(session!=null)
				session.close();
		}
	}
	
	/**
	 * This method help to delete data in the database  
	 * @param entity the object of data to be deleted.
	 */	
	public static void delete(Object entity)
	{
		Session session = null;
		Transaction tx = null;
		try 
		{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.delete(entity);
			tx.commit();
		}
		catch(HibernateException e)
		{
			System.out.println(e.toString());
		}
		finally
		{
			if(session!=null)
				session.close();
		}
	}
	
	/**
	 * This method help to delete data in the database  
	 * @param entity the object of data to be deleted.
	 */	
	@SuppressWarnings("rawtypes")
	public static Object get(Class clazz,Serializable id)
	{
		Session session = null;
		try
		{
			session = HibernateUtil.getSession();
			Object obj = session.get(clazz,id);
			return obj;
		}
		catch(HibernateException e)
		{
			e.printStackTrace();
			return null;
		}
		finally
		{
			if(session!=null)
				session.close();
		}
	}
}
